package se.sll.service.catalogue.common.provider;

import java.util.Iterator;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import lombok.extern.slf4j.Slf4j;
import se.sll.service.catalogue.common.exception.ConstraintViolationException;

/**
 *
 * @author Christer Palm, Nogui
 */
@Slf4j
@Provider
public class ConstraintViolationExceptionHandler implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException e) {
        Response.ResponseBuilder responseBuilder = Response.
                status(Response.Status.BAD_REQUEST).
                header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN + "; charset=UTF-8");

        Set<ConstraintViolation<Object>> constraintViolations = e.getConstraintViolations();
        StringBuilder messages = new StringBuilder();
        Iterator<ConstraintViolation<Object>> constraintViolationIter = constraintViolations.iterator();
        while (constraintViolationIter.hasNext()) {
            ConstraintViolation<Object> constraintViolation = constraintViolationIter.next();

            String property = constraintViolation.getPropertyPath().toString();
            messages.append(property);
            messages.append(": ");
            String message = constraintViolation.getMessage();
            messages.append(message);

            String messageTemplate = constraintViolation.getMessageTemplate();
            responseBuilder.header("X-ErrorCode", messageTemplate);

            if (constraintViolationIter.hasNext()) {
                messages.append("\n");
            }
        }
        responseBuilder.entity(messages.toString());
        log.info("Constraint violation in REST service: " + messages, e);

        return responseBuilder.build();
    }
}
